package com.chinadrtv.batch.admin.controller.ozing;

import com.chinadrtv.batch.admin.service.OzingCardBatchService;
import com.chinadrtv.user.service.ozing.OzingCardService;
import com.chinadrtv.batch.admin.util.Constants;
import com.chinadrtv.user.model.OzingCard;
import com.chinadrtv.user.model.OzingCardBatch;
import com.chinadrtv.user.model.User;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * User: Jack.Chen
 * Date: 13-1-15
 */
@Controller
public class OzingCardExportController extends AbstractExcelView{
    private final SimpleDateFormat ymdhms_sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private OzingCardBatchService ozingCardBatchService;

    @Autowired
    private OzingCardService ozingCardService;

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        List<OzingCard> ozingCards = (List<OzingCard>) model.get("ozingCards");
        OzingCardBatch ozingCardBatch = (OzingCardBatch) model.get("ozingCardBatch");


        int page = 1000;
        int i = 0;
        short r = 0;
        HSSFSheet sheet = null;
        int sheetIndex = -1;
        HSSFRow row = null;
        CreationHelper createHelper = workbook.getCreationHelper();
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));
        for (OzingCard ozingCard : ozingCards) {
            if (i % page == 0) {
                r = 0;
                sheetIndex++;
                sheet = workbook.createSheet((i + 1) + "-" + (i + 1 + page));

                //create title row
                row = sheet.createRow(r);
                HSSFCell cardId_cell = row.createCell(0);
                HSSFCell cardPassword_cell = row.createCell(1);
                HSSFCell cardPeriod_cell = row.createCell(2);
                HSSFCell cardPeriodType_cell = row.createCell(3);
                HSSFCell cardDeadLine_cell = row.createCell(4);
                HSSFCell cardValue_cell = row.createCell(5);


                cardId_cell.setCellValue("卡号");
                cardPassword_cell.setCellValue("卡密");
                cardPeriod_cell.setCellValue("有效期");
                cardPeriodType_cell.setCellValue("有效期类型");
                cardDeadLine_cell.setCellValue("截止日期");
                cardValue_cell.setCellValue("面值");
                r++;
            }
            sheet = workbook.getSheetAt(sheetIndex);
            row = sheet.createRow(r);
            HSSFCell cardId_cell = row.createCell(0);
            HSSFCell cardPassword_cell = row.createCell(1);
            HSSFCell cardPeriod_cell = row.createCell(2);
            HSSFCell cardPeriodType_cell = row.createCell(3);
            HSSFCell cardDeadLine_cell = row.createCell(4);

            cardId_cell.setCellValue(ozingCard.getCardId());
            cardPassword_cell.setCellValue(ozingCard.getCardPassword());
            cardPeriod_cell.setCellValue(ozingCard.getCardValidityPeriod());
            cardPeriodType_cell.setCellValue(ozingCard.getCardValidityPeriodType().name());
            cardDeadLine_cell.setCellStyle(cellStyle);
            cardDeadLine_cell.setCellValue(ozingCard.getCardActivationDeadline());

            if (ozingCard.getCardSalePrice() != null) {
                HSSFCell cardSalePrice_cell = row.createCell(5);
                cardSalePrice_cell.setCellValue(ozingCard.getCardSalePrice());
            }
            r++;
            i++;
        }


        String exportName = ozingCardBatch.getId() + ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + exportName);
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    @RequestMapping(value = "/ozing/cards/excel", method = RequestMethod.GET)
    public ModelAndView exportExcel(@RequestParam(required = true) String batchId, ModelMap model,
                                    HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
        OzingCardBatch ozingCardBatch = ozingCardBatchService.get(Long.valueOf(batchId));
        if(ozingCardBatch.isMakeCardLock()){
            return null;
        }
        List<OzingCard> ozingCards = ozingCardService.getAllByBatch(Long.valueOf(batchId));

        model.put("ozingCards", ozingCards);
        model.put("ozingCardBatch", ozingCardBatch);
        OzingCardExportController viewExcel = new OzingCardExportController();
        return new ModelAndView(viewExcel, model);

    }

    @RequestMapping(value = "/ozing/cards/lock", method = RequestMethod.GET)
      public String lock(@RequestParam(required = true) String batchId,
                         HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        ozingCardBatchService.lock(Long.valueOf(batchId), getCurrentUser(request));
        return null;
    }

    @RequestMapping(value = "/ozing/cards/unlock", method = RequestMethod.GET)
    public @ResponseBody Object unlock(@RequestParam(required = true) String batchId,
                       HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

        return ozingCardBatchService.unlock(Long.valueOf(batchId), getCurrentUser(request));
    }


    private User getCurrentUser(HttpServletRequest request) {
        SecurityContext ctx = (SecurityContext) request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        return (User) ctx.getAuthentication().getPrincipal();
    }
}
